//
//  MZYheadTableViewController.m
//  WristWatch
//
//  Created by dllo on 15/10/22.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "MZYheadTableViewController.h"
#import "MZYHeader.h"
#import "MZYInfoDetailViewController.h"
#import "MZYheadTableViewCell.h"
#import "MZYheadWebTableViewController.h"
#import "MZYsurplusViewController.h"
#import "SaveTool.h"


@interface MZYheadTableViewController ()<UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UISearchBarDelegate>
@property(nonatomic, retain)UIScrollView *scrollView;
@property(nonatomic, retain)UITableView *headTableView;
@property(nonatomic, retain)NSMutableArray *InfoArr;
@property(nonatomic, retain)NSMutableArray *cellArr;
@property(nonatomic, retain)UIImageView *imageView;
@property(nonatomic, retain)MBProgressHUD *HUD;
@property(nonatomic, assign)NSInteger page;
@property(nonatomic, retain)UIButton *oneButton;
@property(nonatomic, retain)UIButton *twoButton;
@property(nonatomic, retain)UIButton *threeButton;
@property(nonatomic, retain)UIButton *fourButton;
@property(nonatomic, retain)UISearchBar *searchBar;

@property(nonatomic, retain)UILabel *countLabel;
@property(nonatomic, assign)NSTimer *mytimer;

@property(nonatomic, retain)NSMutableArray *huancunArr;



@end

@implementation MZYheadTableViewController

- (void)dealloc {
    [_scrollView release];
    [_headTableView release];
    [_InfoArr release];
    [_cellArr release];
    [_imageView release];
    [_HUD release];
    [_oneButton release];
    [_twoButton release];
    [_threeButton release];
    [_fourButton release];
    [_searchBar release];
    [_countLabel release];
    [_huancunArr release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    // 建立tableView
    self.cellArr = [NSMutableArray array];
    self.InfoArr = [NSMutableArray array];
    self.title = @"资讯";
    
    
    [SaveTool isHaveFolder];
    
    [self createTableView];

    // 解析数据
    [self createData];
    // 自动轮播
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(hahaha) userInfo:nil repeats:YES];
}
- (void)hahaha{
    static NSInteger i = 0;
    self.scrollView.contentOffset = CGPointMake(self.view.frame.size.width * i, 0);
    if (self.scrollView.contentOffset.x == self.InfoArr.count * WIDTH) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
//        [self.mytimer setFireDate:[NSDate distantFuture]];
        i = 0;
    }
    
    i++;
    
}

#pragma mark 建立headTableView
- (void)createTableView {
    self.headTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 55) style:UITableViewStylePlain];
    self.headTableView.rowHeight = 120;

    [self.view addSubview:self.headTableView];
    [_headTableView release];
    
    self.headTableView.dataSource = self;
    self.headTableView.delegate = self;


    //下拉
    self.headTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(header)];
    //上啦
    self.headTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footer)];
    
    self.page = 1;
    
    
    // 建立小菊花
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"正在加载";
    self.HUD.detailsLabelText = @"请稍后";
    self.HUD.dimBackground = YES;
    
    
//
//#pragma mark 第五个界面的newsTableView
//    self.newsTableView = [[UITableView alloc] initWithFrame:CGRectMake(WIDTH * 4, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
//    [self.bigScrollView addSubview:self.newsTableView];
//    [_newsTableView release];
//    
//    self.newsTableView.dataSource = self;
//    self.newsTableView.delegate = self;
//    
//
//
//#pragma mark 最后一个showCollectionView
//    UICollectionViewFlowLayout *showflowLayout = [[UICollectionViewFlowLayout alloc] init];
//    showflowLayout.itemSize = CGSizeMake(WIDTH / 2 - 15, WIDTH / 3 + 10);
//    showflowLayout.minimumInteritemSpacing = 10;
//    showflowLayout.minimumLineSpacing = 10;
//    showflowLayout.sectionInset = UIEdgeInsetsMake(0, 20, 10, 10);
//    
//    self.showCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(WIDTH * 5, 0, WIDTH, HEIGHT - 99) collectionViewLayout:showflowLayout];
//    [self.bigScrollView addSubview:self.showCollectionView];
//    [self.showCollectionView release];
//    self.showCollectionView.backgroundColor = [UIColor whiteColor];
//    
//    self.showCollectionView.dataSource = self;
//    self.showCollectionView.delegate = self;
//    
//    [self.showCollectionView registerClass:[MZYshowCollectionViewCell class] forCellWithReuseIdentifier:@"reuseru"];
    
    
//    //下拉
//    self.showCollectionView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(head)];
//    //上啦
//    self.showCollectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(foot)];
//
//    self.page = 1;
    


}



#pragma mark 上拉下拉方法
//下拉
- (void)header {
    //把已经刷新的数据删除,否则越刷新重复数据越多
    [self.InfoArr removeAllObjects];
    [self createData];

}
//上拉
-(void)footer {
    self.page += 2;
        NSLog(@"%ld",(long)self.page);
    NSString *url = [NSString stringWithFormat:@"http://www.xbiao.com/app/articlelist?&pages=%ld&type=1&time=1445388475218", (long)self.page];
    
    
    // 解析UITableView
    AFHTTPRequestOperationManager *Tabmanager = [AFHTTPRequestOperationManager manager];
    [Tabmanager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *zArr = responseObject;
        for (NSDictionary *tempDic in zArr) {
            MZYInformationModel *info = [[MZYInformationModel alloc] init];
            [info setValuesForKeysWithDictionary:tempDic];
            [self.cellArr addObject:info];
            [info release];
        }
        if (self.cellArr.count > 0) {
//            self.HUD.hidden = YES;
            [self.headTableView reloadData];
        }
        
        [self.headTableView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}




//#pragma mark -bigScrollView
//- (void)creatBigScrollView {
//    self.bigScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH , HEIGHT - 44)];
//    self.bigScrollView.contentSize = CGSizeMake(WIDTH * 6, 0);
//    self.bigScrollView.pagingEnabled = YES;
//    [self.view addSubview:self.bigScrollView];
//
//}

#pragma mark 解析数据
- (void)createData {
    // 解析轮播图
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://www.xbiao.com/app/articleimage" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *mArr = responseObject;
        
        for (NSDictionary *tempDic in mArr) {
            MZYInformationModel *info = [[MZYInformationModel alloc] init];
            [info setValuesForKeysWithDictionary:tempDic];
            [self.InfoArr addObject:info];
            [info release];
        }
        if (self.InfoArr.count > 0) {
            [self.headTableView reloadData];
            [self createScrollView];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
    // 解析UITableView
    
    
    NSURL *url = [NSURL URLWithString:@"http://www.xbiao.com/app/articlelist?&pages=0&type=1&time=1445680661076"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            
            
            self.huancunArr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            
            
            
            NSMutableArray *zArr = self.huancunArr;
            self.cellArr = [NSMutableArray array];
            
            for (NSDictionary *tempDic in zArr) {
                MZYInformationModel *info = [[MZYInformationModel alloc] init];
                [info setValuesForKeysWithDictionary:tempDic];
                [self.cellArr addObject:info];
                
                if ([SaveTool isHaveMovieInPlist:info]) {
                    [SaveTool saveMovieToPlist:info];
                }
                
                    [info release];
            }
                
                if (self.cellArr.count > 0) {
                self.HUD.hidden = YES;
                [self.headTableView reloadData];
                [self createScrollView];
      }
            [self.headTableView.header endRefreshing];
  }
            
            }];
    
    NSURLCache *cache = [NSURLCache sharedURLCache];
    NSCachedURLResponse *response = [cache cachedResponseForRequest:request];
    if (response) {
        NSLog(@"源这个请求已存在缓存");
    } else {
        NSLog(@"源这个请求没有缓存");
    }
    
    
    
    
    
    
    
    
//    AFHTTPRequestOperationManager *Tabmanager = [AFHTTPRequestOperationManager manager];
//    [Tabmanager GET:@"http://www.xbiao.com/app/articlelist?&pages=0&type=1&time=1445388475218" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSMutableArray *zArr = responseObject;
//        self.cellArr = [NSMutableArray array];
//        for (NSDictionary *tempDic in zArr) {
//            MZYInformationModel *info = [[MZYInformationModel alloc] init];
//            [info setValuesForKeysWithDictionary:tempDic];
//            [self.cellArr addObject:info];
//            
//            if ([SaveTool isHaveMovieInPlist:info]) {
//                [SaveTool saveMovieToPlist:info];
//            }
//            
//            [info release];
//        }
//        
//        if (self.cellArr.count > 0) {
//            self.HUD.hidden = YES;
//            [self.headTableView reloadData];
//            [self createScrollView];
//        }
//        [self.headTableView.header endRefreshing];
//        
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        
//    }];
    
    


}


#pragma mark 标题栏
//- (void)creatHeader {
//    // 建立标题栏
//    self.headerScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, 50)];
////    self.headerScrollView.backgroundColor = [UIColor redColor];
//    [self.view addSubview:self.headerScrollView];
//        [_headerScrollView release];
//    
//    self.headerScrollView.showsHorizontalScrollIndicator = NO;
//    self.headerScrollView.contentSize = CGSizeMake(WIDTH / 2 * 3, 0);
//    
//    NSArray *arr = @[@"头条资讯", @"热点新闻", @"精品秀", @"最新发布", @"媒体看点", @"show time"];
//    for (NSInteger i = 0; i < arr.count; i++) {
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//        button.frame = CGRectMake(90 * i, 0, 90, 50);
//        button.tag = 1000 * (i + 1);
//        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        [button setTitle:arr[i] forState:UIControlStateNormal];
//        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
//        [self.headerScrollView addSubview:button];
//    }
//
//}

#pragma mark 轮播图和button
- (void)createScrollView {
    // 建立轮播图
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT / 2 + 20)];
    self.headTableView.tableHeaderView = view;
    view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [view release];
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, HEIGHT / 2.25 + 14, WIDTH, HEIGHT / 14.5)];
    [view addSubview:titleLabel];
    titleLabel.text = @"头条资讯";
//    titleLabel.textColor = [UIColor redColor];
    titleLabel.backgroundColor = [UIColor whiteColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.textAlignment = 1;
    [titleLabel release];

    
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/ 3.5 + 5)];
    [view addSubview:self.scrollView];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.bounces = NO;
    self.scrollView.delegate = self;
    // 移动的范围
    self.scrollView.contentSize = CGSizeMake(self.InfoArr.count * WIDTH, 0);
//    [self.scrollView setContentOffset:CGRectMake(0, 0, self.InfoArr.count * WIDTH, 0) animated:YES];
    // 按页滚动
    self.scrollView.pagingEnabled = YES;
    [_scrollView release];
    // 用户交互
    self.scrollView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.scrollView addGestureRecognizer:tap];
        [tap release];
        // 点几下才能触发的方法
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
    
    
    for (NSInteger i = 0; i < self.InfoArr.count; i++) {
        MZYInformationModel *info = self.InfoArr[i];
        self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * i, 0, WIDTH, HEIGHT/ 3.5 + 5)];
        [self.imageView sd_setImageWithURL:[NSURL URLWithString:info.img] placeholderImage:[UIImage imageNamed:@"3.jpg"]];
        [self.scrollView addSubview:self.imageView];
        self.imageView.userInteractionEnabled = YES;
        [_imageView release];
        
//        UIImageView *LastImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WIDTH * self.InfoArr.count, 0, WIDTH, 180)];
//        [LastImageView sd_setImageWithURL:[NSURL URLWithString:[self.InfoArr[0]img]] placeholderImage:[UIImage imageNamed:@"3.jpg"]];
//        [self.scrollView addSubview:LastImageView];
//        [LastImageView release];
//        LastImageView.userInteractionEnabled = YES;
//
//        // 为了能显示第一张图片, 我们需要先设置一下偏移量, 这样能直接显示照片名为1.jpg的图片
//        self.scrollView.contentOffset = CGPointMake(WIDTH, 0);
        
        
//        // 创建一个pageControl
//        self.pager = [[UIPageControl alloc] initWithFrame:CGRectMake(100, 600, 200, 40)];
//        self.pager.backgroundColor = [UIColor blackColor];
//        [self.view addSubview:self.pager];
//        [_pager release];
//        self.pager.numberOfPages = 6;
//        // 设置未被点的颜色
//        self.pager.pageIndicatorTintColor = [UIColor redColor];
//        // 选中的点得颜色
//        self.pager.currentPageIndicatorTintColor = [UIColor yellowColor];
//        //
//        [self.pager addTarget:self action:@selector(pageAction:) forControlEvents:UIControlEventValueChanged];
//        // 想要scrollview实现缩放功能, 需要先设置的最大最小的缩放比例
//        //    self.scrollView.minimumZoomScale = 0.5;
//        //    self.scrollView.maximumZoomScale = 2;
        
        self.countLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 40 + self.view.frame.size.width * i, HEIGHT / 4 - 15, 45, 50)];
        self.countLabel.text = [NSString stringWithFormat:@"%ld/%ld", i + 1, (unsigned long)self.InfoArr.count];
        self.countLabel.textColor = [UIColor whiteColor];
        [self.scrollView addSubview:self.countLabel];
        [self.countLabel release];
        

        
    
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH * i, HEIGHT / 4 - 15, WIDTH - 45, 50)];
        label.textColor = [UIColor whiteColor];
        label.text = info.title;
        [self.scrollView addSubview:label];
        [label release];
        
    }
    
    self.oneButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.oneButton.frame = CGRectMake(10, HEIGHT / 3.5 + 15, WIDTH / 4.5, HEIGHT / 7);
    [view addSubview:self.oneButton];
    [self.oneButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.oneButton setBackgroundImage:[UIImage imageNamed:@"4.jpg"] forState:UIControlStateNormal];
    self.oneButton.layer.cornerRadius = 10;
    [self.oneButton setClipsToBounds:YES];
    
    
    self.twoButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.twoButton.frame = CGRectMake(WIDTH / 4.5 + 17, HEIGHT / 3.5 + 15, WIDTH / 4.5, HEIGHT / 7);
    [view addSubview:self.twoButton];
    [self.twoButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.twoButton setBackgroundImage:[UIImage imageNamed:@"5.jpg"] forState:UIControlStateNormal];
    self.twoButton.layer.cornerRadius = 10;
    [self.twoButton setClipsToBounds:YES];
    
    
    self.threeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.threeButton.frame = CGRectMake(WIDTH / 4.5 * 2 + 24, HEIGHT / 3.5 + 15, WIDTH / 4.5, HEIGHT / 7);
    self.threeButton.layer.cornerRadius = 10;
    [view addSubview:self.threeButton];
    [self.threeButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.threeButton setBackgroundImage:[UIImage imageNamed:@"6"] forState:UIControlStateNormal];
    self.threeButton.layer.cornerRadius = 10;
    [self.threeButton setClipsToBounds:YES];
    
    
    self.fourButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.fourButton.frame = CGRectMake(WIDTH / 4.5 * 3 + 31, HEIGHT / 3.5 + 15, WIDTH / 4.5, HEIGHT / 7);
    [view addSubview:self.fourButton];
    [self.fourButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.fourButton setBackgroundImage:[UIImage imageNamed:@"7"] forState:UIControlStateNormal];
    self.fourButton.backgroundColor = [UIColor whiteColor];
    self.fourButton.layer.cornerRadius = 10;
    [self.fourButton setClipsToBounds:YES];
    
}


#pragma mark tableView的协议方法
// tableView协议必须实现的第一个方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cellArr.count;

}
// tableView协议必须实现的第二个方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    MZYheadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[MZYheadTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    MZYInformationModel *info = self.cellArr[indexPath.row];
    cell.titleLabel.text = info.title;
    NSString *str = [info.inputtime substringToIndex:11];
    cell.timeLabel.text = str;
    cell.brandLabel.text = info.brand_name;
    [cell.titleImageView sd_setImageWithURL:[NSURL URLWithString:info.img] placeholderImage:[UIImage imageNamed:@"3.jpg"]];
    
    return cell;

}


// 添加到ScrollView上的button的点击方法
- (void)buttonAction:(UIButton *)button {
    NSLog(@"我被点击了");
    if (button == self.oneButton) {
        MZYhotTableViewController *hotVC = [[MZYhotTableViewController alloc] init];
        hotVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:hotVC animated:YES];
        [hotVC release];
    } else if (button == self.twoButton) {
        MZYFineViewController *fineVC = [[MZYFineViewController alloc] init];
        fineVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:fineVC animated:YES];
        [fineVC release];
    } else if (button == self.threeButton) {
        MZYnewsViewController *newsVC = [[MZYnewsViewController alloc] init];
        newsVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:newsVC animated:YES];
        [newsVC release];
    } else {
        MZYsurplusViewController *surVC = [[MZYsurplusViewController alloc] init];
        surVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:surVC animated:YES];
        [surVC release];
    }
    
}
#pragma mark 轮播图web跳转
- (void)tapAction:(UITapGestureRecognizer *)tap {
    NSLog(@"我被点击了😠");
    MZYInfoDetailViewController *infoVC = [[MZYInfoDetailViewController alloc] init];
    MZYInformationModel *tem = [[MZYInformationModel alloc] init];
    for (NSInteger i = 0; i < self.InfoArr.count; i++) {
        if (self.scrollView.contentOffset.x == i * WIDTH) {
            tem = self.InfoArr[i];
            infoVC.url = tem.url;
            infoVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:infoVC animated:YES];
        }
    }
    
}

#pragma mark TableView 跳转web下一界面
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"我被点击了😠");
    MZYheadWebTableViewController *htabVC = [[MZYheadWebTableViewController alloc] init];
    htabVC.hidesBottomBarWhenPushed = YES;
    MZYInformationModel *info = self.cellArr[indexPath.row];
    htabVC.url = info.url;
    [self.navigationController pushViewController:htabVC animated:YES];
    [htabVC release];
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
